package com.yoomiito.app.act;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.core.widget.NestedScrollView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.zxing.WriterException;
import com.gyf.barlibrary.ImmersionBar;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.adapter.act.free.PersonalGoodsAdapter;
import com.yoomiito.app.adapter.act.free.FreeGoodsAdapter;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.home.FreeActList;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.ConfigUtils;
import com.yoomiito.app.utils.DateUtils;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.ImageLoader;
import com.yoomiito.app.utils.ImageUtils;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.LoginUtils;
import com.yoomiito.app.utils.RouterUtils;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.utils.ZxingUtil;
import com.yoomiito.app.utils.wx.UMengShareUtils;
import com.yoomiito.app.widget.SpacesItemDecoration;
import com.yoomiito.app.widget.dialog.ShareBottomDialog_1;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class FreeBuyActivity extends BaseActivity<FreeBuyPresenter> {

    @BindView(R.id.zero_goods_rcy)
    RecyclerView mFreeRcy;
    @BindView(R.id.personal_goods_rcy)
    RecyclerView mPersonalGoodsRcy;
    @BindView(R.id.timer_container)
    LinearLayout mTimeContainerLl;
    @BindView(R.id.time_ll)
    LinearLayout mTimeLl;
    @BindView(R.id.scroll_view)
    NestedScrollView mScrollView;
    @BindView(R.id.old_time_container)
    LinearLayout mOldContainerLl;
    @BindView(R.id.title_bar)
    LinearLayout mTitleBarLl;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.day)
    TextView mDayTv;
    @BindView(R.id.minute)
    TextView mMinuteTv;
    @BindView(R.id.hour)
    TextView mHourTv;
    @BindView(R.id.second)
    TextView mSecondTv;
    @BindView(R.id.act_rule)
    TextView mRuleTv;
    @BindView(R.id.show_name)
    TextView showNameTv;

    private ShareBottomDialog_1 shareDialog;
    private Bitmap shareBitmap;
    private String id;
    private FreeActList freeActList;
    private FreeGoodsAdapter freeGoodsAdapter;
    private PersonalGoodsAdapter personalGoodsAdapter;
    private Disposable disposable;

    @Override
    public int getLayoutId() {
        return R.layout.act_free_buy;
    }

    @Override
    public FreeBuyPresenter newP() {
        return new FreeBuyPresenter(App.mAppConfig);
    }


    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this).keyboardEnable(false).init();
    }

    public static void start(Context context, String id) {
        Intent intent = new Intent(context, FreeBuyActivity.class);
        intent.putExtra(Constant.ID, id);
        context.startActivity(intent);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        id = getIntent().getStringExtra(Constant.ID);
        mTitleBarLl.getBackground().setAlpha(0);
        initScrollView();
        mRefreshLayout.setOnRefreshListener(() -> {
            getP().getFreeGoodsList(id);
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        mFreeRcy.setHasFixedSize(true);
        mFreeRcy.setNestedScrollingEnabled(false);
        freeGoodsAdapter = new FreeGoodsAdapter(null);
        freeGoodsAdapter.setOnItemClickListener((adapter, view, position) -> {
            RouterUtils.toGoodsDetail(FreeBuyActivity.this,
                    id + "&" + freeGoodsAdapter.getData().get(position).getProduct_id(),
                    AllCode.FreeBuyGoods);
        });
        mFreeRcy.setLayoutManager(layoutManager);
        mFreeRcy.setItemAnimator(new DefaultItemAnimator());
        mFreeRcy.setAdapter(freeGoodsAdapter);
        mFreeRcy.setFocusable(false);

        LinearLayoutManager layoutManager_1 = new LinearLayoutManager(this);
        personalGoodsAdapter = new PersonalGoodsAdapter(null);
        personalGoodsAdapter.setOnItemClickListener((adapter, view, position) ->
                RouterUtils.toGoodsDetail(FreeBuyActivity.this,
                        personalGoodsAdapter.getData().get(position).getProduct_id(), AllCode.TaoBao)

        );
        personalGoodsAdapter.setOnItemChildClickListener((adapter, view, position) ->
                RouterUtils.toGoodsDetail(FreeBuyActivity.this,
                        personalGoodsAdapter.getData().get(position).getProduct_id(), AllCode.TaoBao)

        );
        mPersonalGoodsRcy.addItemDecoration(new SpacesItemDecoration(DensityUtil.dp2px(16)));
        mPersonalGoodsRcy.setLayoutManager(layoutManager_1);
        mPersonalGoodsRcy.setItemAnimator(new DefaultItemAnimator());
        mPersonalGoodsRcy.setAdapter(personalGoodsAdapter);
        mPersonalGoodsRcy.setNestedScrollingEnabled(false);
        showLoading();
        getP().getFreeGoodsList(id);

    }

    private void initScrollView() {
        mScrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY - oldScrollY < 0) {//下滑
                if (scrollY <= DensityUtil.dp2px(154) && mOldContainerLl.getChildCount() == 0) {
                    mTimeContainerLl.removeAllViews();
                    mOldContainerLl.addView(mTimeLl);
                    mTitleBarLl.getBackground().setAlpha(0);
                }
            }
            if (scrollY - oldScrollY > 0) {//上滑

                if (scrollY >= DensityUtil.dp2px(154) && mTimeContainerLl.getChildCount() == 0) {
                    mOldContainerLl.removeAllViews();
                    mTimeContainerLl.addView(mTimeLl);
                    mTitleBarLl.getBackground().setAlpha(255);

                }
            }
        });
    }

    public void setFreeGoods(FreeActList freeActList) {
        dismissLoading();
        mRefreshLayout.setRefreshing(false);
        this.freeActList = freeActList;
        disposable();
        downTime(freeActList.getDistance_time());
        freeGoodsAdapter.setNewData(freeActList.getProdunt());
        personalGoodsAdapter.setNewData(freeActList.getSpecial_product());
        mRuleTv.setText(freeActList.getDes());
        if (freeActList.getFree_success()==null||freeActList.getFree_success().size()==0){
            return;
        }
        Observable.interval(0, 7000, TimeUnit.MILLISECONDS)
                .compose(bindToLifecycle())
                .map(aLong -> {
                    int po = (int) (aLong % freeActList.getFree_success().size());
                    return freeActList.getFree_success().get(po);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> {
                    if (showNameTv.getVisibility() == View.GONE) {
                        showNameTv.setVisibility(View.VISIBLE);
                    }
                    showNameTv.setText(aLong + "成功免单");
                    AnimationSet aset = new AnimationSet(true);
                    AlphaAnimation aa = new AlphaAnimation(0, 1);
                    aa.setDuration(500);
                    aset.addAnimation(aa);
                    aset.setFillAfter(true);
                    showNameTv.startAnimation(aset);
//                    showNameTv.setVisibility(View.VISIBLE);
                })
                .delay(4, TimeUnit.SECONDS)
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        AnimationSet aset = new AnimationSet(true);
                        AlphaAnimation aa = new AlphaAnimation(1, 0);
                        aa.setDuration(500);
                        aset.addAnimation(aa);
                        aset.setFillAfter(true);
                        showNameTv.startAnimation(aset);
                    }
                })
                .subscribe();
    }

    private void downTime(long time) {
        if (disposable == null) {
            disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
                    .take(time + 1)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext(aLong -> {
                                L.i("S:" + aLong);
                                setTime(time - aLong);
                            }
                    )
                    .doOnComplete(() -> {
                        L.i("开始请求");
                        disposable = null;
                        YMToast.showText("活动已结束");
//                        getP().getFreeGoodsList(id);
                    })
                    .subscribe();
        }


    }

    private void setTime(long time) {
        String[] s = DateUtils.stamp2time(time);
        mDayTv.setText(s[0]);
        mHourTv.setText(s[1]);
        mMinuteTv.setText(s[2]);
        mSecondTv.setText(s[3]);
    }

    @OnClick({R.id.back, R.id.share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.share:
                if (App.mAppConfig.getIsLogin()){
                    showShareDialog();
                }else {
//                    AllUtils.toLogin(FreeBuyActivity.this, AllCode.LoginIn);
                    LoginUtils.INSTANCE.toOneKeyLogin(this);

                }
                break;
        }
    }

    private void showShareDialog() {
        if (shareDialog == null) {
            shareDialog = new ShareBottomDialog_1(this);
            shareDialog.setOnShareItemClickListener(type -> {
                shareDialog.dismiss();
                switch (type) {
                    case 1://wx
                        UMengShareUtils.shareWX(FreeBuyActivity.this, freeActList.getShare_desc(),
                                ConfigUtils.getInstance().getReTaoBaoUrl() + "/app/freeorder/?id=" + id + "&code=" + UserInfoConfig.getInviteCode(),
                                freeActList.getShare_title(),
                                freeActList.getShare_img());
                        break;
                    case 2://朋友圈
                        AllUtils.requestPermission(FreeBuyActivity.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE)
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(aBoolean -> {
                                    if (aBoolean) {
                                        showLoading();
                                        makeAdPic();
                                        dismissLoading();
                                        UMengShareUtils.shareWXPic(SHARE_MEDIA.WEIXIN_CIRCLE, this, shareBitmap);
                                    }
                                });
                        break;
                    case 3://save photo
                        AllUtils.requestPermission(FreeBuyActivity.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE)
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(aBoolean -> {
                                    if (aBoolean) {
                                        showLoading();
                                        makeAdPic();
                                        dismissLoading();
                                        ImageLoader.getInstance().downloadPic(FreeBuyActivity.this, shareBitmap);
                                        YMToast.showText("保存成功");
                                    }
                                });
                        break;
                }
            });
        }
        shareDialog.show();
    }

    private void makeAdPic() {
        View view = LayoutInflater.from(this).inflate(R.layout.ad_free_buy, null, false);

        TextView actDateTv = view.findViewById(R.id.free_date);
        actDateTv.setText(freeActList.getStart_time() + "~" + freeActList.getEnd_time());

        TextView inviteCodeTv = view.findViewById(R.id.invite_code);
        inviteCodeTv.setText(UserInfoConfig.getInviteCode());

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        RecyclerView rcy = view.findViewById(R.id.free_goods);
        rcy.setLayoutManager(layoutManager);
        FreeGoodsAdapter freeGoodsAdapter = new FreeGoodsAdapter(freeActList.getProdunt().size() > 3 ? freeActList.getProdunt().subList(0, 3) : freeActList.getProdunt());
        rcy.setAdapter(freeGoodsAdapter);
        rcy.setNestedScrollingEnabled(false);
        ImageView erWMIv = view.findViewById(R.id.erweima);
        try {
            erWMIv.setImageBitmap(ZxingUtil.cretaeZxing(ConfigUtils.getInstance().getDownloadApkUel(), getResources().getColor(R.color.color_black)));
        } catch (WriterException e) {
            e.printStackTrace();
        }

        ImageUtils.layoutView(view);
        shareBitmap = ImageUtils.viewSaveToImage(view);
    }


    private void disposable() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }

//    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
//    public void updateData(EventMessage eventMessage) {
//        if (Constant.UPDATE_DATA.equals(eventMessage.getEventType())) {
//            if (eventMessage.getCode() == AllCode.FreeBuyGoods) {
//                getP().getFreeGoodsList(id);
//            }
//        }
//    }

    public void finishAct() {
        this.finish();
    }

    @Override
    protected void onStart() {
        super.onStart();
//        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        disposable();
        super.onDestroy();
    }
}
